package Utils;

import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.UpdateOptions;
import org.bson.Document;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class Tools {
    public static void consoleInfo(String msg){
        SimpleDateFormat ft =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("[" + ft.format(new Date()) + "] - " + msg);
    }

    public static List<String> getDateList(String startDateStr, String endDateStr){
        /**
         * 解析startDate至endDate之间所有的日期，转换成str，组成list返回
         *
         */
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateList = new ArrayList<>();
        try {
            Date startDate = simpleDateFormat1.parse(startDateStr);
            Date endDate = simpleDateFormat1.parse(endDateStr);
            Calendar calendar = Calendar.getInstance();
            for (Date i = startDate; endDate.compareTo(i) >= 0 ; i = calendar.getTime()) {
                dateList.add(simpleDateFormat1.format(i));
                calendar.setTime(i);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("检查日期格式（yyyy-MM-dd）！");
            return null;
        }

        return dateList;
    }


    public static void updateToDb(MongoCollection collection, Document doc){
        BasicDBObject query = new BasicDBObject().append("_id", doc.get("_id"));
        BasicDBObject obj = new BasicDBObject("$set", doc);
        collection.updateOne(query, obj, (new UpdateOptions()).upsert(true));
        consoleInfo("update to db: " + doc);
    }
}
